import os
import datetime
from django.shortcuts import render
from django.http import JsonResponse
from fdfs_client.client import Fdfs_client, get_tracker_conf

from FileManager.models import FileManager

def index(request):
    file_list = FileManager.objects.order_by("-change_time")
    return render(request,"index.html",locals())


def upload(request):
    result = {"code": "","data": [],"state": ""}
    if request.method == "POST":
        file = request.FILES.get("file")
        file_name = file.name

        client = os.path.join(
            os.path.dirname(__file__),"client.conf"
        )

        tracker_path = get_tracker_conf(client)
        try:
            client = Fdfs_client(tracker_path)
            ret = client.upload_by_buffer(file.read(), file_ext_name = file_name)
        except Exception as e:
            result["code"] = 500
            result["state"] = str(e)
            result["data"].append(str(e))
        else:
            f = FileManager()
            f.file_name = file_name
            f.remote_name = ret.get("Remote file_id").decode()
            f.upload_size = ret.get("Uploaded size")
            f.file_type = "图片"
            f.upload_time = datetime.datetime.now()
            f.change_time = datetime.datetime.now()
            f.group_name = ret.get("Group name").decode()
            f.storage_ip = ret.get("Storage IP").decode()
            f.save()
            result["code"] = 200
            result["state"] = "上传成功"
            result["data"].append({
                    "file_name": file_name,
                    "file_size": f.upload_size,
                    "file_id": f.id
            })
    else:
        result["code"] = 403
        result["state"] = "请求失败"
        result["data"].append("请求失败")
    return JsonResponse(result)

def file_info(request,id):
    file = FileManager.objects.filter(id = id).first()

    if file:
        host = "http://192.168.194.158/"
        src = host+file.remote_name.replace("b'","").replace("'","")
        suffix = file.file_name.rsplit(".")[1]
        imgs = ["jpg","jpeg","png","gif"]
        video = ["mp4","avi"]
        if suffix in imgs:
            label = "img"
        elif suffix in video:
            label = "video"
        else:
            label = "none"
    return render(request,"file_info.html",locals())


def download(request):
    result = {"code": "", "data": [], "state": ""}
    id_list = request.GET.getlist("file")
    for id in id_list:
        file = FileManager.objects.filter(id=id).first()

        if file:
            client = os.path.join(
                os.path.dirname(__file__), "client.conf"
            )
            tracker_path = get_tracker_conf(client)
            client = Fdfs_client(tracker_path)
            filename = file.file_name
            remote_name = file.remote_name.replace("b'","").replace("'","")
            with open(filename,"wb") as f:

                content = client.download_to_buffer(remote_name.encode())
                f.write(content["Content"])
            result["code"] = 200
            result["data"].append("下载完成")
            result["state"] = "下载完成"
        else:
            result["code"] = 400
            result["data"].append("id 为 %s的文件不存在"%id)
            result["state"] = "不完整下载"
            continue

    return JsonResponse(result)

#Create your views here.
